package com.heima.wemedia.filter;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(1)
@WebFilter(filterName = "wmTokenFilter",urlPatterns = "/*")
public class WmTokenFilter extends GenericFilterBean {

    /**
     * 此过滤器主要作用是 如果有人访问自媒体 首先过滤器先从请求头中把wmUserId拿出来
     * 然后设置到线程变量中 供后方服务使用
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String wmUserIdStr = request.getHeader("wmUserId");

        if (StringUtils.isNotBlank(wmUserIdStr)){
            Integer wmUserId = Integer.valueOf(wmUserIdStr);
            WmUser wmUser = new WmUser();
            wmUser.setId(wmUserId);
            WmThreadLocalUtils.setUser(wmUser);
        }

        filterChain.doFilter(request,response);

    }
}
